package com.ash.util;

import com.alibaba.druid.pool.DruidDataSource;


import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/8 16:34
 * @Author : Chen Chao
 * @File : connection.com.ash.util.ConnectionsUtil.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
public class ConnectionsUtil {
    protected static String url;
    protected static String user;
    protected static String password;
    protected static String className;
    protected static DruidDataSource ds;
    static {
        Properties properties = new Properties();
        try (FileReader fileReader = new FileReader
                ("resource/connection.properties")
        ) {
            /*加载配置*/
            properties.load(fileReader);
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            className = properties.getProperty("className");

            /*驱动只要加载一次，所以放在static代码块中*/
            Class.forName(className);

            /*创建数据库连接池，加载配置信息*/
            ds = new DruidDataSource();
            ds.setDriverClassName(className);
            ds.setUsername(user);
            ds.setPassword(password);
            ds.setUrl(url);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接池
     * @return 数据库连接池
     */
    public static DruidDataSource getDataSource(){
        return ds;

    }
    /**
     * 获取数据库连接
     *
     * @return 返回数据库连接
     */
    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭数据库资源,Connection对象会回到连接池中
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
      ConnectionUtil.close(connection, statement, resultSet);
    }
}